<template>
    <view class="home h100vh df fdc">
        <hy-statusheight></hy-statusheight>
        <view class="picbox1">
            <image
                class="homeimg"
                src="/static/pic/login.png"
                mode="widthFix"
                @click="gohomeFn"
            />
        </view>
        <view class="picbox2">
            <image
                class="logo"
                src="/static/pic/login-logo.png"
                mode="widthFix"
            />
        </view>
        <view class="wrinting">
            <text class="word">真学历 真技能 真教育</text>
        </view>
        <view class="formbox">
            <wd-form ref="form" :model="formData" :rules="rules">
                <wd-input
                    :maxlength="11"
                    no-border
                    prop="phone"
                    type="number"
                    clearable
                    v-model="formData.phone"
                    placeholder="请输入手机号"
                    @blur="blurChange('phone')"
                />
                <wd-gap height="36rpx"></wd-gap>
                <wd-input
                    :maxlength="6"
                    no-border
                    prop="code"
                    type="number"
                    clearable
                    v-model="formData.code"
                    placeholder="请输入验证码"
                    @blur="blurChange('code')"
                >
                    <template #suffix>
                        <view class="code" @click="getCode">{{ tips }}</view>
                    </template>
                </wd-input>
                <view class="wz">未注册的手机号验证后将自动创建账号</view>
                <view class="footer">
                    <wd-gap height="80rpx"></wd-gap>
                    <wd-button
                        type="primary"
                        size="large"
                        @click="handleSubmit"
                        block
                        custom-class="sub-btn"
                        :loading="submitLoading"
                    >
                        登录
                    </wd-button>
                </view>
            </wd-form>
        </view>
        <uv-code
            :keepRunning="true"
            ref="uCodeRef"
            seconds="30"
            @start="disabled1 = true"
            @end="disabled1 = false"
            @change="codeChange"
            startText="获取验证码"
            endText="获取验证码"
        ></uv-code>
        <view class="submitbtn"></view>
        <view class="radiolocation tac">
            <view class="radiobox df ac jc" style="padding: 0 32rpx">
                <wd-checkbox
                    v-model="checkboxValue"
                    size="large"
                    checked-color="#ff2c2c"
                >
                    <view class="radiotest">
                        我已阅读并同意
                        <text class="link" @tap.stop="linkFn(1)">
                            《用户协议》
                        </text>
                        和
                        <text class="link" @tap.stop="linkFn(2)">
                            《隐私协议》
                        </text>
                    </view>
                </wd-checkbox>
            </view>
            <view class="banben_chunk" v-if="banbenOBJ">
                {{ url }}.{{ banbenOBJ.version }}.{{ banbenOBJ.versionCode }}
            </view>
        </view>
    </view>
</template>

<script setup lang="ts">
import { getCodebyPost_API, login_API, basicInfo_API } from '@/server/home/home'
import { useUserStore } from '@/stores'
import { FormRules } from '@/uni_modules/wot-design-uni/components/wd-form/types'
import { signReturnFn, strReturnFn } from '@/utils/transferUtils'

const store = useUserStore()
const banbenOBJ = ref({
    version: uni.getAppBaseInfo().appVersion, //是manifest的 '应用版本名称'
    versionCode: uni.getAppBaseInfo().appVersionCode, //是manifest的 '应用版本号'
})
const url = ref()
/**
 * 获取版本信息的函数
 *
 * 根据编译平台的不同，设置不同的 URL 值
 */
const banbenGetFn = () => {
    // #ifdef APP-HARMONY
    url.value =
        import.meta.env.HY_SERVER_BASEURL.split(':')[0] == 'http'
            ? 'local'
            : 'active'
    // #endif
    // #ifdef H5
    url.value =
        import.meta.env.HY_SERVER_BASEURL.split(':')[0] == 'http'
            ? 'h5-local'
            : 'h5-active'
    // #endif
}
/**
 * 跳转到首页
 */
const gohomeFn = () => {
    uni.switchTab({ url: '/pages/home/home' })
}
onLoad(() => {
    banbenGetFn()
})
/**
 * 导航函数
 * @param {string} type 类型
 */
const linkFn = (type) => {
    uni.navigateTo({ url: `/pages/index/agreement?id=${String(type)}` })
}

// 复选框选中状态
const checkboxValue = ref(false)
const form = ref()
const rules: FormRules = {
    phone: [
        { required: true, message: '此为必填字段' },
        {
            validator: (value) => {
                return uni.$uv.test.mobile(value)
            },
            message: '手机号格式错误',
            required: true,
        },
    ],
    code: [{ required: true, message: '此为必填字段' }],
}
// 表单绑定值
const formData = reactive({
    phone: '',
    code: '',
})
const submitLoading = ref(false)
const handleSubmit = () => {
    form.value
        .validate()
        .then(({ valid, errors }) => {
            if (valid) {
                console.log('checkboxValue.value:', checkboxValue.value)
                if (!checkboxValue.value)
                    return uni.$uv.toast('请阅读并勾选下方协议')
                toSubmitFn()
            }
        })
        .catch((error) => {
            console.log(error, 'error')
        })
}

const toSubmitFn = async () => {
    if (submitLoading.value) return
    //清空用户信息
    store.clearUserAll()
    submitLoading.value = true
    const res = await login_API({ ...formData, client: 'app' })
    if (res.code === 200) {
        uni.$uv.toast('登录成功')
        store.token = res.data.access_token //设置token
        store.isLogin = true //设置登录状态
        await store.GetBasicInfo()
        submitLoading.value = false
        await gohomeFn()
    } else {
        submitLoading.value = false
        uni.$uv.toast(res.msg)
    }
}
const disabled1 = ref(false)
const tips = ref('')
const uCodeRef = ref()
// 从开始到结束之间，每秒触发一次，获得提示的文字
const codeChange = (text) => {
    tips.value = text
}
const blurChange = (el) => {
    form.value.validate([el])
}
const getCode = () => {
    if (disabled1.value) {
        return uni.$uv.toast('请等待倒计时结束再点击！')
    }
    form.value
        .validate(['phone'])
        .then(async ({ valid, errors }) => {
            if (!uni.$uv.test.mobile(formData.phone)) {
                uni.$uv.toast('请先输入您的手机号')
                return
            }
            if (valid) {
                if (!uCodeRef.value) return
                if (uCodeRef.value.canGetCode) {
                    const data = {
                        apiKey: 'i0vJWwoUVN5lkoSR',
                        phone: formData.phone,
                        timestamp: strReturnFn(),
                        sign: 'dsfjgerghrtyfgdfsre',
                    }
                    const res = await getCodebyPost_API({
                        ...data,
                        sign: signReturnFn(data),
                    })
                    if (res.code === 200 && res.data) {
                        uni.$uv.toast('验证码已发送')
                        uCodeRef.value.start()
                    }
                } else {
                    uni.$uv.toast('请等待倒计时结束再点击！')
                }
            }
        })
        .catch((error) => {
            console.log(error, 'error')
        })
}
</script>

<style lang="scss" scoped>
.home {
    .picbox1 {
        padding: 22rpx 0 20rpx 32rpx;

        .homeimg {
            width: 48rpx;
            display: block;
        }
    }

    .picbox2 {
        padding-top: 60rpx;
        text-align: center;

        .logo {
            width: 192rpx;
        }
    }

    .wrinting {
        padding-top: 16rpx;
        padding-bottom: 112rpx;
        text-align: center;

        .word {
            font-size: 40rpx;
            font-weight: 550;
            letter-spacing: 7rpx;
        }
    }

    .code {
        color: #ff2c2c;
        margin-left: 20rpx;
    }
}

:deep(.wd-input__suffix) {
    display: flex;
}

.radiolocation {
    margin-top: auto;
    margin-bottom: 70rpx;

    .radiotest {
        font-size: 24rpx;

        .link {
            color: $hy-color-host-red;
        }
    }
}

:deep(.wd-input__value) {
    border-radius: 80rpx;
    background-color: $hy-color-login-input;
    border-color: rgba(255, 0, 0, 0) !important;
    font-size: 24rpx;
    padding: 28rpx 30rpx 28rpx 30rpx !important;
}

:deep(.wd-input__clear) {
    background: none;
}

:deep(.wd-input__error-message) {
    padding: 0 30rpx;
}

.formbox {
    padding: 0 32rpx 52rpx 32rpx;

    .sub-btn {
        background-color: #ff2c2c;
    }
}

.footer {
    :deep(.wd-button__text) {
        color: #ffffff;
    }
}

.banben_chunk {
    margin-top: 18rpx;
    font-size: 24rpx;
    text-align: center;
    color: #999999;
}

.wz {
    color: #999999;
    font-size: 24rpx;
    margin-top: 20rpx;
    padding: 0 30rpx;
}
</style>
